# Create your views here.
import os
from Batch_Call.models import Task
from Call.packaging import seats_status
from utils.open_files import file_iterator
from django.http import StreamingHttpResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from Batch_Call.packaging import queue_mappings, create_server, update_server, retrieve_server, start_server, \
    stop_server, query_relation_seats, query_queues, create_queues, update_queues, delete_queues, retrieve_task, \
    create_task, update_task, start_task, stop_task, add_leads, query_finally_id, query_template, import_data, \
    query_thread, query_group_name, retrieve_task2
from zb_outbound.settings import BASE_DIR




# 队列绑定/解绑坐席
class Queue_Mappings_View(APIView):
    def get(self,request):
        pass
    def post(self,request):
        # 绑定/解绑类别
        action = request.data.get('action','')
        # 坐席工号
        agentNo = request.data.get('agentNo','')
        # 队列id
        queueId = request.data.get('queueId','')
        # print('队列绑定/解绑坐席',action,agentNo,queueId)
        res = queue_mappings(action=action,agentNo=agentNo,queueId=queueId)
        return Response(res)

    def put(self,request):
        pass
    def delete(self,request):
        pass

# 生成队列ID
class Queue_Generate_View(APIView):
    def post(self,request):
        # 打上个队列ID
        queue_number = query_finally_id()
        if queue_number == 500:
            return Response({"code":500,"msg":"系统繁忙"})
        new_queue = int(queue_number.split('Q')[-1]) + 1
        return Response({"code":200,"msg":"请求成功","queue_number":'Q' + str(new_queue)})

# 查询队列下关联的所有坐席
class Query_Relation_Seats_View(APIView):
    def get(self,request):
        # 队列号
        queue_number = request.GET.get('queue_number')
        return Response(query_relation_seats(queue_number))
    def post(self,request):
        pass

# 队列
class Queues_View(APIView):
    def get(self,request):
        queueIds = request.GET.data('queueIds',[])
        res = query_queues(queueIds=queueIds)
        return Response(res)
    def post(self,request):
        queueId = request.data.get('queueId','')
        description = request.data.get('description','')
        priority = request.data.get('priority','')
        userCli = request.data.get('userCli','')
        prompt = request.data.get('prompt','')
        timeout = request.data.get('timeout','')
        res = create_queues(queueId=queueId,description=description,priority=priority,userCli=userCli,prompt=prompt,timeout=timeout)
        return Response(res)
    def put(self,request):
        queueId = request.data.get('queueId', '')
        description = request.data.get('description', '')
        priority = request.data.get('priority', '')
        userCli = request.data.get('userCli', '')
        prompt = request.data.get('prompt', '')
        timeout = request.data.get('timeout', '')
        res = update_queues(queueId=queueId, description=description, priority=priority, userCli=userCli, prompt=prompt,
                            timeout=timeout)
        return Response(res)
    def delete(self,request):
        queueId = request.data.get('queueId', '')
        res = delete_queues(queueId=queueId)
        return Response(res)

# 服务
class Server_View(APIView):
    def get(self,request):
        bcsId = request.GET.get('bcsId', '')
        page = request.GET.get('page', '')
        pageSize = request.GET.get('pageSize', '')
        res = retrieve_server(bcsId=bcsId, page=page, pageSize=pageSize)
        return Response(res)
    def post(self,request):
        queueId = request.data.get('queueId','')
        friendlyName = request.data.get('friendlyName','')
        mode = request.data.get('mode','')
        userCli = request.data.get('userCli','')
        ccr = request.data.get('ccr','')
        tuning = request.data.get('tuning','')
        workDay = request.data.get('workDay','')
        workTime = request.data.get('workTime','')
        res = create_server(queueId=queueId,friendlyName=friendlyName,mode=mode,userCli=userCli,ccr=ccr,tuning=tuning,workDay=workDay,workTime=workTime)
        return Response(res)
    def put(self,request):
        # 服务唯一标识
        bcsId = request.data.get('bcsId', '')
        tuning = request.data.get('tuning', '')
        userCli = request.data.get('userCli', '')
        friendlyName = request.data.get('friendlyName', '')
        queueId = request.data.get('queueId', '')
        mode = request.data.get('mode', '')
        ccr = request.data.get('ccr', '')
        workDay = request.data.get('workDay', '')
        workTime = request.data.get('workTime', '')
        res = update_server(bcsId=bcsId, tuning=tuning, userCli=userCli, friendlyName=friendlyName, queueId=queueId,
                            mode=mode, ccr=ccr, workDay=workDay, workTime=workTime)
        return Response(res)
    def delete(self,request):
        pass

# 启动服务
class Start_Server_View(APIView):
    def get(self,request):
        pass
    def post(self,request):
        bcsId = request.data.get('bcsId','')
        res = start_server(bcsId=bcsId)
        return Response(res)
    def put(self,request):
        pass
    def delete(self,request):
        pass

# 停止服务
class Stop_Server_View(APIView):
    def get(self,request):
        pass
    def post(self,request):
        bcsId = request.data.get('bcsId','')
        res = stop_server(bcsId=bcsId)
        return Response(res)
    def put(self,request):
        pass
    def delete(self,request):
        pass

# 任务
class Task_View(APIView):
    def get(self,request):
        account_tag = request.GET.get('account_tag','')
        page = request.GET.get('page',1)
        page_size = request.GET.get('page_size',10)
        res = retrieve_task(account_tag=account_tag,page=page,page_size=page_size)
        return Response(res)
    def post(self,request):
        bcsId = request.data.get('bcsId', '')
        # 任务名称
        friendlyName = request.data.get('friendlyName', '')
        mode = request.data.get('mode', '')
        server_ccr = request.data.get('server_ccr', '')
        tuning = request.data.get('tuning', '')
        call_way = request.data.get('call_way','')
        queue_id = request.data.get('queue_id','')
        group_id = request.data.get('group_id','')
        priority = request.data.get('priority', '')
        batch = request.data.get('batch', '')
        beginTime = request.data.get('beginTime', '')
        endTime = request.data.get('endTime','')
        userCli = request.data.get('userCli', '')
        username = request.data.get('username', '')
        ccr = request.data.get('ccr', '')
        account_tag = request.data.get('account_tag', '')
        template_id = request.data.get('template_id', '')
        state = request.data.get('state', '')
        # 有效工作日
        work_day = request.data.get('work_day','')
        # 有效工作时间
        work_time = request.data.get('work_time','')
        if call_way == '1':
            res = create_task(work_day=work_day,work_time=work_time,mode=mode,username=username,server_ccr=server_ccr,tuning=tuning,bcsId=bcsId,friendlyName=friendlyName,call_way=call_way,queue_id=queue_id,group_id=group_id,priority=priority,batch=batch,beginTime=beginTime,endTime=endTime,userCli=userCli,ccr=ccr,account_tag=account_tag,template_id=template_id,state=state)
            return Response(res)
        else:
            return Response({"code":403,"msg":"功能暂未开放"})
    def put(self,request):
        taskId = request.data.get('taskId', '')
        bcsId = request.data.get('bcsId', '')
        # 任务名称
        friendlyName = request.data.get('friendlyName', '')
        call_way = request.data.get('call_way', '')
        priority = request.data.get('priority', '')
        batch = request.data.get('batch', '')
        template_id = request.data.get('template_id', '')
        beginTime = request.data.get('beginTime', '')
        endTime = request.data.get('endTime', '')
        userCli = request.data.get('userCli', '')
        ccr = request.data.get('ccr', '')
        state = request.data.get('state', '')
        mode = request.data.get('mode', '')
        server_ccr = request.data.get('server_ccr', '')
        tuning = request.data.get('tuning', '')
        # 有效工作日
        work_day = request.data.get('work_day', '')
        # 有效工作时间
        work_time = request.data.get('work_time', '')
        res = update_task(mode=mode,server_ccr=server_ccr,tuning=tuning,work_day=work_day,work_time=work_time,taskId=taskId,bcsId=bcsId,friendlyName=friendlyName,call_way=call_way, priority=priority, batch=batch, beginTime=beginTime,endTime=endTime,userCli=userCli, template_id=template_id,ccr=ccr, state=state)
        return Response(res)
    def delete(self,request):
        try:
            taskId = request.data.get('taskId', '')
            for i in taskId.split(','):
                Task.objects.filter(task_id=i).first().delete()
            return Response({"code":200,"msg":"删除成功"})
        except:
            return {"code":500,"msg":"请检查传入参数"}


# 启动任务
class Start_Task_View(APIView):
    def post(self,request):
        print('启动任务',request.data)
        bcsId = request.data.get('bcsId','')
        taskId = request.data.get('taskId','')
        res = start_task(bcsId=bcsId,taskId=taskId)
        return Response(res)

# 停止任务
class Stop_Task_View(APIView):
    def post(self,request):
        bcsId = request.data.get('bcsId', '')
        taskId = request.data.get('taskId', '')
        res = stop_task(bcsId=bcsId, taskId=taskId)
        return Response(res)

# 添加线索
class Add_Leads_View(APIView):
    def post(self,request):
        bcsId = request.data.get('bcsId', '')
        taskId = request.data.get('taskId', '')
        leads = request.data.get('leads', [])
        res = add_leads(bcsId=bcsId,taskId=taskId,leads=leads)
        return Response(res)

# 文件测试接口
class File_Test_View(APIView):
    def get(self,request):
        excel_name = "test.xlsx"
        path = os.path.join(BASE_DIR, 'temp', excel_name)
        print(path)
        response = StreamingHttpResponse(file_iterator(path))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename={}'.format(excel_name)
        return response

# 语音文件测试接口
class Voice_Test_View(APIView):
    def get(self,request):
        excel_name = "test.mp3"
        path = os.path.join(BASE_DIR, 'voice', excel_name)
        print(path)
        response = StreamingHttpResponse(file_iterator(path))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename={}'.format(excel_name)
        return response

# 模板
class Template_View(APIView):
    def get(self,request):
        account_id = request.GET.get('account_id', '')
        # 查询企业下的所有模板
        res = query_template(account_id=account_id)
        return Response(res)
    def post(self,request):
        res = import_data(request)
        return Response(res)
    def put(self,request):
        pass
    def delete(self,request):
        pass

# Batch_Call_Details
class Batch_Call_Details_View(APIView):
    def get(self,request):
        queue_id = request.GET.get('queue_id','')
        task_id = request.GET.get('task_id','')
        try:
            seats_list = query_relation_seats(queue_id)
            seats_number_list = seats_list['data'].get('seats_number',[])
            # 工作中
            working = 0
            # 空闲
            idle = 0
            # 置忙
            busy = 0
            # 离线
            off_line = 0
            # 查询坐席状态
            for seats in seats_number_list:
                S = seats_status(agentNo=seats)
                data = S.get('data', [])
                if data:
                    if data[0].get('callState','') == 'ringing' or data[0].get('callState','') == 'connected':
                        working += 1
                    if data[0].get('callState', '') == 'idle' and data[0].get('sipStatus', '') == '1' and data[0].get('workStatus', '') == '1':
                        idle += 1
                    if data[0].get('workStatus', '') == '2':
                        busy += 1
                    if data[0].get('workStatus', '') == '0':
                        off_line += 1
            # 坐席总数
            seats_count = len(seats_number_list)
            task = Task.objects.filter(id=task_id).first()
            # 呼叫名单总数
            call_list_count = len(query_thread(batch=task.batch))
            # 创建时间
            create_time = str(task.create_time).split('.')[0]
            # 模板名称
            group_name = query_group_name(task.queue_id)
            # 任务名称
            task_name = task.task_name
            # 呼叫模式
            mode = task.mode
            if mode == '1':
                mode = '固定并发'
            else:
                mode = '智能并发'
            # 完成度
            dict_data = {
                "task_name":task_name,
                "group_name":group_name,
                "create_time":create_time,
                "call_list_count":call_list_count,
                "seats_count":seats_count,
                "working":working,
                "idle":idle,
                "busy":busy,
                "off_line":off_line,
                "completeness":"",
                "mode":mode
            }
            return Response({"code":200,"msg":"ok","data":[dict_data]})
        except Exception as e:
            print(e)
            return Response({"code": 500, "msg": "系统繁忙","error":str(e)})